<?php

namespace app\controller;

use app\BaseController;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use Lib\Crypt;
use think\captcha\facade\Captcha;
use think\facade\Cookie;
use think\response\Json;

class Api extends BaseController
{
    /**
     *游戏内置社区登录
     *
     **/
    public function login(): Json
    {
        $user = request()->get('user');
        $pass = request()->get('pass');
        if (empty($user) || empty($pass)) return pr(300, '用户名或密码不可为空'); else {
            $p = Crypt::Encode($pass);
            $f = $this->M("user")->field('password,token,id,nickname,account,head_img,stat')->where(['account' => $user])->find();        
            if (empty($f)) {
                $this->M('log_login')->insert(['uid' => 0, 'ip' => getUserIp(), 'time' => time(), 'method' => "API登录", 'state' => "登录失败[用户不存在]"]);
                return pr(300, '不存在的用户');
            }
            if ($f['password'] != $p) {
                $this->M('log_login')->insert(['uid' => $f['id'], 'ip' => getUserIp(), 'time' => time(), 'method' => "API登录", 'state' => "登录失败[密码错误]"]);
                return pr(301, '密码错误');
            }
            if ($f['stat'] == 0) {
                $this->M('log_login')->insert(['uid' => $f['id'], 'ip' => getUserIp(), 'time' => time(), 'method' => "API登录", 'state' => "登录失败[账号已锁定]"]);
                return pr(301, '账号已锁定');
            }
            $this->M('user')->where(['id' => $f['id']])->save(['last_login_time' => time(), 'last_login_ip' => getUserIp()]);
            $this->M('log_login')->insert(['uid' => $f['id'], 'ip' => getUserIp(), 'time' => time(), 'method' => "API登录", 'state' => "登录成功"]);
            $role_ids = $this->M("user_role")->where(['uid' => $f['id']])->column('role_id');
            $role_ids_string = implode(',', $role_ids);
            return pr(200, '登陆成功', ['accessToken' => $f['token'], 'nickName' => $f['nickname'], 'user' => $f['account'], 'loginTime' => time(),'role' => $role_ids_string]);
        }
    }

    /**
     * 获取验证码
     */
    public function getVerifyImage()
    {
        return Captcha::create();
    }


    public function test($token)
    {
        return pr(200, hCaptcha($token));

    }

    /**
     * 使用腾讯云发送短信验证码
     */
    public function sendSMS()
    {

    }

    /**
     * 获取服务器信息
     */
    public function getServerInfo($ip = '', $port = 28887): Json
    {
        try {
            if ($ip == null) return pr(900, "请正确传入ip地址");
            $sendStr = '08 05 00 00 00 eb 60 60 04 00';  //发送16进制查询请求到服务器
            $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
            socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 3, "usec" => 0));
            $sendStrArray = str_split(str_replace(' ', '', $sendStr), 2);
            if (!socket_connect($socket, $ip, $port)) return pr(500, "服务器连接失败");
            for ($j = 0; $j < count($sendStrArray); $j++) {
                socket_write($socket, chr(hexdec($sendStrArray[$j])));
            }
            $receiveStr = socket_read($socket, 1024, PHP_BINARY_READ);
            $receiveStrHex = gzinflate(substr(bin2hex($receiveStr), 68));
            if (!str_starts_with($receiveStrHex, "08")) return pr(901, "服务器返回值不是预期");
            $model = match (substr($receiveStrHex, -14, -12)) {
                "00" => "创造",
                "01" => "无害",
                "02" => "挑战",
                "03" => "残酷",
                "04" => "冒险",
                default => null
            };
            $maxPlayer = hexdec(substr($receiveStrHex, -16, -14) . substr($receiveStrHex, -18, -16));
            $onlinePlayer = hexdec(substr($receiveStrHex, -20, -18) . substr($receiveStrHex, -22, -20));
            $version = hex2bin(substr($receiveStrHex, 12, -22));
            socket_close($socket);
            return pr(200, "此服务器可访问", array('version' => $version, 'maxPlayer' => $maxPlayer, 'onlinePlayer' => $onlinePlayer, 'model' => $model));
        } catch (Exception $e) {
            return pr(500, "拉取失败[可能是暂时的]", $e);
        }
    }

    /**
     * 获取QQ登录二维码
     */
    public function getQQLoginQRCode()
    {
        $cookieJar = new CookieJar();
        $client = new Client(['cookies' => $cookieJar]);
        $randomNumber = "0." . mt_rand() . mt_rand();
        $randomNumber = substr($randomNumber, 0, 20);
        try {
            $response = $client->request('GET', "https://ssl.ptlogin2.qq.com/ptqrshow?appid=549000912&e=2&l=M&s=3&d=72&v=4&t=" . $randomNumber . "&pt_3rd_aid=0", ['headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) QQBrowser/10.5.3863.400 Chrome/79.0.3945.130 Safari/537.36',]]);
            $cookie = $response->getHeader("Set-Cookie")[0];
            $ptqrtoken = substr($cookie, strpos($cookie, '=') + 1, strpos($cookie, ';') - strpos($cookie, '=') - 1);
            setcookie("ptqrtoken", $ptqrtoken, time() + 3600 * 24 * 365, '/');
            return response($response->getBody(), 200, ["Content-Type" => "image/png"]);
        } catch (GuzzleException $e) {
            return pr(301, '获取二维码时失败:' . $e->getMessage());
        }
    }

    /**
     * 获取QQ登录二维码状态 [暂不可用]
     */
    public function getQQLoginState()
    {
        $ptqrtoken = Cookie::get('ptqrtoken');
        $cookieJar = new CookieJar();
        $client = new Client(['cookies' => $cookieJar]);
        try {
            $response = $client->request('GET', 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?proxy_url=https://qzs.qq.com/qzone/v6/portal/proxy.html&daid=5&&hide_title_bar=1&low_login=0&qlogin_auto_login=1&no_verifyimg=1&link_target=blank&appid=549000912&style=22&target=self&s_url=https://qzs.qzone.qq.com/qzone/v5/loginsucc.html?para=izone&pt_qr_app=手机QQ空间&pt_qr_link=http://z.qzone.com/download.html&self_regurl=https://qzs.qq.com/qzone/v6/reg/index.html&pt_qr_help_link=http://z.qzone.com/download.html&pt_no_auth=1', ['headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) QQBrowser/10.5.3863.400 Chrome/79.0.3945.130 Safari/537.36',]]);
            $cookie = $response->getHeader("Set-Cookie")[1];
            $loginSig = substr($cookie, strpos($cookie, '=') + 1, strpos($cookie, ';') - strpos($cookie, '=') - 1);

            //生成action
            $action = '0-1-' . time() . mt_rand(100, 999);
            $url = "https://ssl.ptlogin2.qq.com/ptqrlogin?u1=https://qzs.qzone.qq.com/qzone/v5/loginsucc.html?para=izone&ptqrtoken=" . $ptqrtoken . "&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=" . $action . "&js_ver=19112817&js_type=1&login_sig=" . $loginSig . "&pt_uistyle=40&aid=549000912&daid=5&";

            $response = $client->request('GET', $url, ['headers' => ["Referer" => "https://xui.ptlogin2.qq.com/", "Host" => "ssl.ptlogin2.qq.com", 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) QQBrowser/10.5.3863.400 Chrome/79.0.3945.130 Safari/537.36',]]);
            $result = $response->getBody();
            return json($result);
        } catch (GuzzleException $e) {
            return pr(301, '验证二维码时失败:' . $e->getMessage());
        }
    }
}